<?php

namespace app\admin\controller\xilujob;

use app\admin\model\User;
use app\admin\model\xilujob\EnterpriseInfo;
use app\common\controller\Backend;
use app\common\model\xilujob\XilujobUser;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\Hook;
use think\Loader;

/**
 * 企业店铺基本信息
 *
 * @icon fa fa-circle-o
 */
class CompanyProfile extends Backend
{
    protected $relationSearch = true;
    protected $multiFields = ['audit_status','personal_audit_status'];
    protected $searchFields = 'enterpriseinfo.company_name,user.email,user.mobile';
    protected $noNeedRight = ['enterprise_info','personal_info'];
    /**
     * CompanyProfile模型对象
     * @var \app\admin\model\xilujob\CompanyProfile
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\xilujob\CompanyProfile;
        $this->view->assign("personalAuditStatusList", $this->model->getPersonalAuditStatusList());
        $this->view->assign("auditStatusList", $this->model->getAuditStatusList());

        $industry_category = \app\admin\model\xilujob\IndustryCategory::order('weigh')->column('id,name');
        $this->assign('industry_categories',$industry_category);
        $this->assignconfig('industry_category',$industry_category);

        $scales = \app\admin\model\xilujob\CompanyScale::column('id,name');
        $this->assign('scales', $scales);

        $company_types = \app\admin\model\xilujob\CompanyProperties::order('weigh')->column('id,name');
        $this->assign('company_types', $company_types);
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user'=>function($q){
                    $q->withField(['id','username','status','nickname','mobile','email','avatar']);
                },'enterpriseinfo'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add() {
        if($this->request->isPost()) {
            $userData = $this->request->post("user/a");
            //$userData['city_id'] = $this->siteCity->city_id;
            $enterpriseData = $this->request->post('row/a');
            $modelData = $this->request->post('model/a');

            if($userData['mobile']) {
                $user = User::where('mobile', $userData['mobile'])->find();
            }
            if(!isset($user) && $userData['email']){
                $user = User::where('email', $userData['email'])->find();
            }
            if(isset($user)){
                $count = $this->model->where('user_id',$user['id'])->count();
                if($count>0){
                    $this->error('当前手机号或邮箱已注册过企业账号');
                }
            }
            Db::startTrans();
            try{
                $company = \app\admin\model\xilujob\XilujobUser::add_user(2, $userData, $enterpriseData, $modelData,$user ?? []);
            }catch (Exception $exception){
                Db::rollback();
                $this->error($exception->getMessage());
            }
            Db::commit();
            $this->success();
        }
        return $this->view->fetch();
    }


    public function edit($ids=null) {

        $model = $this->model->get($ids);
        if (!$model) {
            $this->error(__('No Results were found'));
        }
        $model = \app\admin\model\xilujob\CompanyProfile::get($ids);
        $user = $model->user;
        $row = $model->enterpriseinfo;

        if($this->request->isPost()) {
            $userData = $this->request->post("user/a");
            $enterpriseInfo = $this->request->post('row/a');
            $modelData = $this->request->post('model/a');
            Db::startTrans();
            try{
                $ret = \app\admin\model\xilujob\XilujobUser::edit_user($user->id, 2, $userData, $enterpriseInfo, $modelData);
            }catch (Exception $exception){
                Db::rollback();
                $this->error($exception->getMessage());
            }
            Db::commit();

            $this->success();
        }
//        if($user){
//            $user->mobile = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $user->mobile);
//            if(preg_match("/^1[345789]\d{9}$/", $user->username)){
//                $user->username = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $user->mobile);
//            }
//
//        }
        $provinceId = $row->city_id ? \app\common\model\xilujob\Area::where("id",$row->city_id)->value('pid') : 0;
        $this->assign('model', $model);
        $this->assign('row', $row);
        $this->assign('provinceId', $provinceId);
        $this->assign('user', $user);

        return $this->fetch();
    }


    public function enterprise_info($ids) {
        if(!$this->auth->check('xilujob/company_profile/index')) {
            $this->error(__('You have no permission'));
        }
        $company = $this->model->get($ids);
        $info = \app\admin\model\xilujob\EnterpriseInfo::get(['company_id'=>$ids]);

        if($this->request->isPost()) {
            $params = $this->request->post('row/a');
            Db::startTrans();
            try{
                $company->allowField(['audit_status','refuse_reason'])->save($params);
                if(in_array($company->audit_status,[1,3])){
                    Hook::listen("xilujob_audit_result",$company);
                }
            }catch (Exception $exception){
                Db::rollback();
                $this->error($exception->getMessage());
            }
            Db::commit();

            $this->success();
        }

        $this->view->assign('row',$info);
        $this->view->assign('company',$company);
        return $this->view->fetch('enterprise');
    }

    public function personal_info($ids) {
        if(!$this->auth->check('xilujob/company_profile/index')) {
            $this->error(__('You have no permission'));
        }
        $info = \app\admin\model\xilujob\EnterpriseInfo::get(['company_id'=>$ids]);
        $this->assign('row',$info);
        return $this->fetch('personal');
    }

    public function multi_info($ids) {
        $ids = $ids ? $ids : $this->request->param("ids");
        $this->model = new \app\admin\model\xilujob\EnterpriseInfo();
        if ($ids) {
            if ($this->request->has('params')) {
                parse_str($this->request->post("params"), $values);
                $multiFields = ['daily_resume_action_num','resume_action_num','job_num_limit'];
                $values = array_intersect_key($values, array_flip(is_array($multiFields) ? $multiFields : explode(',', $multiFields)));

                if ($values || $this->auth->isSuperAdmin()) {
                    $adminIds = $this->getDataLimitAdminIds();
                    if (is_array($adminIds)) {
                        $this->model->where($this->dataLimitField, 'in', $adminIds);
                    }

                    $count = 0;
                    Db::startTrans();
                    try {
                        $list = $this->model->where('company_id', 'in', $ids)->select();
                        foreach ($list as $index => $item) {
                            $count += $item->allowField(true)->isUpdate(true)->save($values);
                        }
                        Db::commit();
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    if ($count) {
                        $this->success();
                    } else {
                        $this->error(__('No rows were updated'));
                    }
                } else {
                    $this->error(__('You have no permission'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 批量更新
     *
     * @param $ids
     * @return void
     */
    public function multi($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
//        $refuse_reason = $this->request->post('refuse_reason','');
        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
//        if(isset($values['audit_status']) && $values['audit_status'] == 3 && !$refuse_reason){
//            $this->error("请填写未通过理由");
//        }
//        $values['refuse_reason'] = $refuse_reason;
        if (empty($values)) {
            $this->error(__('You have no permission'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->allowField(true)->isUpdate(true)->save($values);
                if(isset($values['audit_status']) && in_array($values['audit_status'],[1,3])){
                    Hook::listen("xilujob_audit_result",$item);
                }

            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 999999);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if (!empty($this->model) && $relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = $op[$k] ?? '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper($op[$k] ?? $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }
            if($k == 'xilujobuser.first_nickname'){
                $user_ids = User::whereLike("nickname","%$v%")->column('id')?:[0];
                $user_ids = XilujobUser::whereIn('first_pid',$user_ids)->column('user_id')?:[0];
                $where[] = ['company_profile.user_id','in',$user_ids];
                continue;
            }
            if($k == 'xilujobuser.second_nickname'){
                $user_ids2 = User::whereLike("nickname","%$v%")->column('id')?:[0];
                $user_ids2 = XilujobUser::whereIn('second_pid',$user_ids2)->column('user_id')?:[0];
                $where[] = ['company_profile.user_id','in',$user_ids2];
                continue;
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function ($v) {
                            return $v != '' && $v !== false && $v !== null;
                        })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias)
                        && !empty($this->model) && $this->relationSearch) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }


    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        $jobModel = new \app\admin\model\xilujob\Job();
        Db::startTrans();
        try {
            foreach ($list as $item) {
                if($jobModel->where("publisher_id",$item->id)->count()){
                    $this->error("企业有关联职位，不可删除");
                }
                $count += $item->delete();
                $item->enterpriseinfo->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    /**
     * 销毁
     * @param null $ids
     */
    public function destroy($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post('ids');
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $item) {
                $count += $item->delete(true);
                //删除企业资料
                EnterpriseInfo::where('company_id',$item->id)->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }


    public function restore($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $item) {
                $count += $item->restore();
                //还原企业资料
                EnterpriseInfo::where('company_id',$item->id)->update(['deletetime'=>null]);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }
}
